/**
 * 微信授权工具类
 */

// 获取微信授权code
export const getWechatCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				if (res.code) {
					console.log('微信授权code获取成功:', res.code);
					resolve(res.code);
				} else {
					console.error('获取微信授权code失败:', res);
					reject(new Error('获取微信授权code失败'));
				}
			},
			fail: (err) => {
				console.error('微信登录失败:', err);
				reject(err);
			}
		});
	});
};

// 获取微信用户信息
export const getWechatUserInfo = () => {
	return new Promise((resolve, reject) => {
		uni.getUserInfo({
			provider: 'weixin',
			success: (res) => {
				console.log('微信用户信息:', res.userInfo);
				resolve(res.userInfo);
			},
			fail: (err) => {
				console.error('获取微信用户信息失败:', err);
				reject(err);
			}
		});
	});
};

// 检查微信授权状态
export const checkWechatAuth = () => {
	return new Promise((resolve) => {
		uni.getSetting({
			success: (res) => {
				const authSetting = res.authSetting;
				console.log('微信授权设置:', authSetting);
				
				// 检查是否有微信授权
				if (authSetting['scope.userInfo']) {
					resolve(true);
				} else {
					resolve(false);
				}
			},
			fail: () => {
				resolve(false);
			}
		});
	});
};

// 微信手机号授权处理
export const handleWechatPhoneAuth = (e) => {
	return new Promise((resolve, reject) => {
		console.log('微信手机号授权结果:', e);
		
		if (e.detail.errMsg === 'getPhoneNumber:ok') {
			// 用户同意授权
			const phoneData = {
				iv: e.detail.iv,
				encryptedData: e.detail.encryptedData
			};
			console.log('微信手机号授权数据:', phoneData);
			resolve(phoneData);
		} else {
			// 用户拒绝授权
			reject(new Error('用户拒绝授权手机号'));
		}
	});
};

// 微信登录完整流程
export const wechatLoginFlow = async (phoneAuthResult) => {
	try {
		// 1. 获取微信授权code
		const code = await getWechatCode();
		
		// 2. 准备登录数据
		const loginData = {
			code: code,
			iv: phoneAuthResult.iv,
			encryptedData: phoneAuthResult.encryptedData
		};
		
		console.log('微信登录数据:', loginData);
		return loginData;
		
	} catch (error) {
		console.error('微信登录流程失败:', error);
		throw error;
	}
};

// 验证微信授权数据
export const validateWechatAuthData = (data) => {
	if (!data.code || !data.iv || !data.encryptedData) {
		return false;
	}
	return true;
}; 